package com.ljt.springbootwebsocketdemo.starterType;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;

@Slf4j
@Component
public class MyWebSocketHandler extends TextWebSocketHandler {
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException {
        String payload = message.getPayload();
        log.info("收到了 = " + payload);
        TextMessage responseText = new TextMessage("你发送了：" + payload);
        session.sendMessage(responseText);
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        WsSessionManager.add(session.getId(),session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws IOException {
        WsSessionManager.removeAndClose(session.getId());
    }
}